<script>
import { PayContext } from '@/components/storybook/s-pay/pay-context'
import { get, isFunction } from 'lodash'
import { v4 } from 'uuid'

export default {
  name: 'PayConsumer',
  props: {
    component: {
      type: String,
      default: 'span'
    },
    beforePayment: Function,
    afterPayment: Function,
    catchErrorPayment: Function,
    edit: Boolean,
    isMoreUser: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      loading: false
    }
  },
  methods: {
    refresh () {
      this.$store.state.contentIsNeedRefresh = true
      this.$store.state.app.contentIsNeedRefreshCache = true
      this.$nextTick(() => {
        this.$store.state.contentIsNeedRefresh = false
      })
    },
    async openCheckout () {
      try {
        this.loading = true
        const { pay, payCallback, checkoutExistingForItems } = this.$interface.pay

        let subscriptionId = v4()
        let params = null

        if (this.beforePayment && isFunction(this.beforePayment)) {
          params = await this.beforePayment(subscriptionId)
          if (!params) {
            return false
          }
        }
        if (this.edit && params) {
          subscriptionId = params.subscriptionId
        }

        PayContext.instance.openCheckout({
          hostedPage: async () => {
            const event = this.edit ? checkoutExistingForItems : pay

            const { data: response } = await event(params)
            if (response.code !== 0) {
              throw response.msg
            }
            return get(response, 'data.hosted_page')
          },
          success: async () => {
            !this.isMoreUser ? await payCallback({
              key: params.key || null,
              subscriptionId,
              status: true,
              orderStatus: 1
            }) : null;
            this.$emit('success', subscriptionId, PayContext.product)
          },
          loaded: () => {
            this.$emit('loaded')
          },
          error: (error) => {
            if (this.catchErrorPayment && isFunction(this.catchErrorPayment)) {
              this.catchErrorPayment(subscriptionId)
            }
            this.$emit('error', error)
          },
          step: (step) => {
            this.$emit('step')
          },
          close: (e) => {
            if (this.afterPayment && isFunction(this.afterPayment)) {
              this.afterPayment(subscriptionId)
            }
            PayContext.product = null
            PayContext.subscription = null
            PayContext.subscriptionId = null
            PayContext.appId = null
            PayContext.infoModal = false
            PayContext.payModal = null
            this.refresh()
            this.$emit('close')
          }
        })
      } catch (error) {
        console.log(error)
      } finally {
        this.loading = false
      }
    }
  },
  render (h) {
    const childNodes = Object.entries(this.$slots).map(([slot, node]) => h('template', { slot }, node))
    return h(
      this.component,
      {
        attrs: { ...this.$attrs, loading: this.loading },

        on: {
          ...this.$listeners,
          click: this.openCheckout
        }
      },
      [
        childNodes
      ]
    )
  }
}
</script>
